﻿using System;
using System.Web.UI;
using Presenter.Groups;

namespace SocialNetworkClient.Pages.Group
{
    public partial class Home : Page, IGroupHomeView
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Email"] == null && Session["Password"] == null)
                Page.Response.Redirect(@"~/Pages/Error.aspx");

            var id = Request.QueryString["id"];

            if (Session["GroupHomePresenter"] != null)
            {
                var presenter = Session["GroupHomePresenter"] as GroupHomePresenter;
                if (presenter != null)
                    presenter.Reload(this, Convert.ToInt32(id), (string)Session["Email"], (string)Session["Password"]);
            }
            else
            {
                Session["GroupHomePresenter"] = new GroupHomePresenter(this, Convert.ToInt32(id), (string)Session["Email"], (string)Session["Password"]);
            }

            Lb.PostBackUrl = "GroupMessages.aspx?id=" + id;

            LeaveLb.Visible = IsJoined;
            JoinLb.Visible  = !IsJoined;
        }

        protected void LeaveLbClick(object sender, EventArgs e)
        {
            if (Session["Email"] != null && Session["Password"] != null)
            {
                if (UserLeft != null)
                    UserLeft((string)Session["Email"], (string)Session["Password"], Convert.ToInt32(Request.QueryString["id"]));

                Response.Redirect("~/Pages/Group/Home.aspx?id=" + Request.QueryString["id"]);
            }
        }

        protected void JoinLbClick(object sender, EventArgs e)
        {
            if (Session["Email"] != null && Session["Password"] != null)
            {
                if (UserJoined != null)
                    UserJoined((string)Session["Email"], (string)Session["Password"], Convert.ToInt32(Request.QueryString["id"]));

                Response.Redirect("~/Pages/Group/Home.aspx?id=" + Request.QueryString["id"]);
            }
        }

        public void ShowGroup(int id, string type, string title)
        {
            GroupTitleLb.Text = title;
            GroupTypeLb.Text = type;
        }

        public event Action<string, string, int> UserLeft;

        public event Action<string, string, int> UserJoined;
        public bool IsJoined { get; set; }
    }
}